﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.SharePoint;

namespace SpImageCasheSDK
{
    public class SpImageCachePresetsManager
    {
        public const string SpImageCachePresetsListName = "SPImageCachePresets";

        public const string SpImageCacheActionsListName = "SPImageCacheActions";

        class ActionObject
        {
            public ISpImageCacheAction Action;

            public object[] Parameters;
        }

        public static void RunPresetActions(SPListItem spListItem, string presetName)
        {
            if (spListItem != null && !string.IsNullOrEmpty(presetName))
            {
                List<Image> cleaner = new List<Image>();

                try
                {
                    Image image = Image.FromStream(spListItem.File.OpenBinaryStream());

                    cleaner.Add(image);

                    foreach (ActionObject actionObject in GetPresetActions(spListItem.Web, presetName))
                    {
                        image = actionObject.Action.Execute(image, actionObject.Parameters);

                        cleaner.Add(image);
                    }

                    using (MemoryStream stream = new MemoryStream())
                    {
                        image.Save(stream, ImageFormat.Jpeg); //todo

                        spListItem.Web.AllowUnsafeUpdates = true;

                        spListItem.ParentList.RootFolder.Files.Add(spListItem.Url, stream, true);

                        spListItem.Web.AllowUnsafeUpdates = false;
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    foreach (Image image in cleaner)
                    {
                        image.Dispose();
                    }
                }
            }
        }

        private static List<ActionObject> GetPresetActions(SPWeb spWeb, string presetName)
        {
            List<ActionObject> result = new List<ActionObject>();

            SPList spList = spWeb.Lists[SpImageCachePresetsListName];

            SPQuery spQuery = new SPQuery
                                  {
                                      //Folder = spWeb.GetFolder(string.Format("{0}/{1}", SpImageCachePresetsListName, presetName)),
                                      Folder = spList.RootFolder.SubFolders[presetName],

                                      Query = string.Concat("<OrderBy><FieldRef Name='ExecutionOrder' Ascending='FALSE'></FieldRef></OrderBy>"),

                                      ViewFields = string.Concat(
                                      "<FieldRef Name='Title'/>",
                                      "<FieldRef Name='ExecutionOrder'/>",
                                      "<FieldRef Name='SPImageCacheAction'/>",
                                      "<FieldRef Name='SPImageCacheActionParameters'/>"),

                                      ViewFieldsOnly = true
                                  };

            SPListItemCollection spListItemCollection = spList.GetItems(spQuery);

            SPList spImageCacheActionsList = spWeb.Lists[SpImageCacheActionsListName];

            foreach (SPListItem spListItem in spListItemCollection)
            {
                SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(spListItem["SPImageCacheAction"] as string);

                SPListItem spImageCacheActionListItem = spImageCacheActionsList.Items.GetItemById(spFieldLookupValue.LookupId);

                string actionClassName = (string)spImageCacheActionListItem["ActionClassName"];

                ActionObject actionObject = new ActionObject();

                Type actionType = Type.GetType(actionClassName);

                if (typeof(ISpImageCacheAction).IsAssignableFrom(actionType))
                {
                    actionObject.Action = (ISpImageCacheAction)Activator.CreateInstance(actionType);
                }

                string paramString = (string)spListItem["SPImageCacheActionParameters"];

                if (paramString != null)
                    actionObject.Parameters = paramString.Split(',');

                result.Add(actionObject);
            }

            return result;
        }
    }
}
